package com.lvbaoins.Harmony.quartz.controller;

import com.baomidou.mybatisplus.core.metadata.IPage;
import com.lvbaoins.Harmony.base.pojo.page.LayuiPageFactory;
import com.lvbaoins.Harmony.core.base.controller.BaseController;
import com.lvbaoins.Harmony.core.reqres.response.ResponseData;
import com.lvbaoins.Harmony.core.util.ToolUtil;
import com.lvbaoins.Harmony.model.exception.ServiceException;
import com.lvbaoins.Harmony.model.exception.TaskException;
import com.lvbaoins.Harmony.model.util.ValidateUtil;
import com.lvbaoins.Harmony.quartz.domain.SysJob;
import com.lvbaoins.Harmony.quartz.util.CronUtils;
import com.lvbaoins.Harmony.sys.core.exception.enums.BizExceptionEnum;
import com.lvbaoins.Harmony.quartz.service.SysJobService;
import org.quartz.SchedulerException;
import org.quartz.TriggerUtils;
import org.quartz.impl.triggers.CronTriggerImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 定时任务控制器
 *
 * @author gjb
 * @Date 2020-09-15 14:04:23
 */
@Controller
@RequestMapping("/sysJob")
public class SysJobController extends BaseController {

    private String PREFIX = "/sysJob/";

    @Autowired
    private SysJobService sysJobService;

    /**
     * 跳转到定时任务首页
     */
    @RequestMapping("")
    public String index() {
        return PREFIX + "sysJob.html";
    }

    /**
     * 跳转到添加定时任务
     */
    @RequestMapping("/sysJob_add")
    public String sysJobAdd() {
        return PREFIX + "sysJob_add.html";
    }

    /**
     * 跳转到修改定时任务
     */
    @RequestMapping("/sysJob_edit")
    public String sysJobUpdate(String sysJobId) {
        return PREFIX + "sysJob_edit.html";
    }

    /**
     * 跳转到详情定时任务
     */
    @RequestMapping("/sysJob_info")
    public String sysJobInfo(String sysJobId) {
        return PREFIX + "sysJob_info.html";
    }

    /**
     * 生成corn表达式
     * @return
     */
    @RequestMapping("/cron")
    public String corn(){
        return "/cron/cron.html";
    }
    /**
     * 获取定时任务列表
     */
    @RequestMapping(value = "/list")
    @ResponseBody
    public Object list(Integer page, Integer limit, SysJob sysJob) {
        IPage<SysJob> sysJobPage = sysJobService.pageList(page, limit, sysJob);
        return LayuiPageFactory.createPageInfo(sysJobPage);
    }

    /**
     * 新增定时任务
     */
    @RequestMapping(value = "/add")
    @ResponseBody
    public ResponseData add(SysJob sysJob) throws TaskException, SchedulerException {
        if (!CronUtils.isValid(sysJob.getCronExpression())) {
            throw new ServiceException(BizExceptionEnum.CRON_ERROR);
        }
        this.sysJobService.insertJob(sysJob);
        return SUCCESS_TIP;
    }

    /**
     * 删除定时任务
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public ResponseData delete(@RequestParam Long sysJobId) throws SchedulerException {
        if (ToolUtil.isEmpty(sysJobId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        this.sysJobService.deleteJob(sysJobId);
        return SUCCESS_TIP;
    }

    /**
     * 修改定时任务
     */
    @RequestMapping(value = "/edit")
    @ResponseBody
    public ResponseData edit(SysJob sysJob) throws SchedulerException {
        if (ToolUtil.isEmpty(sysJob.getId())) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        sysJobService.updateJob(sysJob);
        return SUCCESS_TIP;
    }

    /**
     * 查看定时任务
     *
     * @author gjb
     */
    @RequestMapping(value = "/view/{sysJobId}")
    @ResponseBody
    public ResponseData view(@PathVariable Long sysJobId) {
        if (ValidateUtil.isEmpty(sysJobId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        SysJob sysJob = this.sysJobService.getById(sysJobId);

        return ResponseData.success(sysJob);
    }

    /**
     * 定时任务详情
     */
    @RequestMapping(value = "/detail/{sysJobId}")
    @ResponseBody
    public ResponseData detail(@PathVariable("sysJobId") Integer sysJobId) {
        if (ToolUtil.isEmpty(sysJobId)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        return ResponseData.success(sysJobService.getById(sysJobId));
    }

    @PostMapping("/run")
    @ResponseBody
    public ResponseData run(Long id) throws SchedulerException {
        if (ToolUtil.isEmpty(id)) {
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
       sysJobService.run(id);
        return SUCCESS_TIP;
    }

    /**
     * 计算cron表达式最近几次的运行时间
     * @param cron
     * @param numTimes
     * @return
     */
    @RequestMapping(value = "/cron", method = RequestMethod.POST)
    @ResponseBody
    public ResponseData corn(String cron, Integer numTimes){
        if(ToolUtil.isOneEmpty(cron)){
            throw new ServiceException(BizExceptionEnum.REQUEST_NULL);
        }
        if( numTimes == null){
            numTimes = 5;
        }
        List<String> list = new ArrayList<>();
        CronTriggerImpl cronTriggerImpl = new CronTriggerImpl();
        try {
            cronTriggerImpl.setCronExpression(cron);
        } catch(ParseException e) {
            e.printStackTrace();
        }
        // 这个是重点，一行代码搞定
        List<Date> dates = TriggerUtils.computeFireTimes(cronTriggerImpl, null, numTimes);
        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        for (Date date : dates) {
            list.add(dateFormat.format(date));
        }
        return ResponseData.success(dates);

    }
}
